import logging

from src.database.models import Product
from src.database.uow import SQLAlchemyUoW

logger = logging.getLogger(__name__)


class ProductService:
    def __init__(self, uow: SQLAlchemyUoW):
        self._uow = uow

    async def create_product(
        self,
        first_name: str,
        last_name: str,
        year: str,
        month: str,
        day: str,
        gender: str,
        house_num: str,
        street_name: str,
        post_code: str,
        login: str,
        password: str,
        email: str,
        category_id: int,
        email_password: str | None = None,
        cpf: str | None = None,
        docs: str | None = None,
    ) -> Product:
        """Создаем товар"""
        product = Product(
            first_name=first_name,
            last_name=last_name,
            year=year,
            month=month,
            day=day,
            gender=gender,
            house_num=house_num,
            street_name=street_name,
            post_code=post_code,
            login=login,
            password=password,
            email=email,
            category_id=category_id,
            email_password=email_password,
            cpf=cpf,
            docs=docs,
        )

        try:
            await self._uow.product_repo.create_product(product)
        except Exception as err:
            await self._uow.rollback()
            raise err

        await self._uow.commit()

        logger.info(f"Product №{product.id} was created")

        return product

    async def get_available_products(
        self, category_id: int, limit: int | None = None
    ) -> list[Product]:
        return await self._uow.product_repo.get_available_products(category_id, limit)
